import 'package:flutter/material.dart';
import '../models/exhibition.dart';
import '../services/exhibition_service.dart';
import '../utils/theme_colors.dart';
import '../widgets/exhibition_card.dart';
import '../widgets/exhibition_filter_sheet.dart';
import 'exhibition_detail_screen.dart';

class CulturalExhibitionScreen extends StatefulWidget {
  const CulturalExhibitionScreen({Key? key}) : super(key: key);

  @override
  State<CulturalExhibitionScreen> createState() => _CulturalExhibitionScreenState();
}

class _CulturalExhibitionScreenState extends State<CulturalExhibitionScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final ExhibitionService _exhibitionService = ExhibitionService.instance;
  
  List<Exhibition> _exhibitions = [];
  List<Exhibition> _filteredExhibitions = [];
  ExhibitionFilter _currentFilter = ExhibitionFilter.all;
  bool _isLoading = true;
  String _searchQuery = '';
  
  final List<String> _tabTitles = ['全部展览', '热门推荐', '即将开展', '虚拟展厅'];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabTitles.length, vsync: this);
    _loadExhibitions();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadExhibitions() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      final exhibitions = await _exhibitionService.getExhibitions();
      setState(() {
        _exhibitions = exhibitions;
        _filteredExhibitions = exhibitions;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载展览失败: $e')),
      );
    }
  }

  void _filterExhibitions() {
    List<Exhibition> filtered = _exhibitions;
    
    // 应用搜索过滤
    if (_searchQuery.isNotEmpty) {
      filtered = filtered.where((exhibition) =>
          exhibition.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          exhibition.description.toLowerCase().contains(_searchQuery.toLowerCase())
      ).toList();
    }
    
    // 应用类型过滤
    if (_currentFilter != ExhibitionFilter.all) {
      filtered = _exhibitionService.filterExhibitions(filtered, _currentFilter);
    }
    
    setState(() {
      _filteredExhibitions = filtered;
    });
  }

  void _showFilterSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => ExhibitionFilterSheet(
        currentFilter: _currentFilter,
        onFilterChanged: (filter) {
          setState(() {
            _currentFilter = filter;
          });
          _filterExhibitions();
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.background,
      appBar: AppBar(
        title: const Text(
          '文化展览',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        backgroundColor: ThemeColors.primary,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.search, color: Colors.white),
            onPressed: _showSearchDialog,
          ),
          IconButton(
            icon: const Icon(Icons.filter_list, color: Colors.white),
            onPressed: _showFilterSheet,
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          isScrollable: true,
          indicatorColor: Colors.white,
          indicatorWeight: 3,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          labelStyle: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
          ),
          tabs: _tabTitles.map((title) => Tab(text: title)).toList(),
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : TabBarView(
              controller: _tabController,
              children: [
                _buildAllExhibitions(),
                _buildHotExhibitions(),
                _buildUpcomingExhibitions(),
                _buildVirtualExhibitions(),
              ],
            ),
    );
  }

  Widget _buildAllExhibitions() {
    return RefreshIndicator(
      onRefresh: _loadExhibitions,
      child: _filteredExhibitions.isEmpty
          ? _buildEmptyState()
          : ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: _filteredExhibitions.length,
              itemBuilder: (context, index) {
                final exhibition = _filteredExhibitions[index];
                return ExhibitionCard(
                  exhibition: exhibition,
                  onTap: () => _navigateToDetail(exhibition),
                  onBookmark: () => _toggleBookmark(exhibition),
                );
              },
            ),
    );
  }

  Widget _buildHotExhibitions() {
    return FutureBuilder<List<Exhibition>>(
      future: _exhibitionService.getHotExhibitions(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        
        if (snapshot.hasError) {
          return _buildErrorState(snapshot.error.toString());
        }
        
        final exhibitions = snapshot.data ?? [];
        if (exhibitions.isEmpty) {
          return _buildEmptyState('暂无热门展览');
        }
        
        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: exhibitions.length,
          itemBuilder: (context, index) {
            final exhibition = exhibitions[index];
            return ExhibitionCard(
              exhibition: exhibition,
              onTap: () => _navigateToDetail(exhibition),
              onBookmark: () => _toggleBookmark(exhibition),
              showHotBadge: true,
            );
          },
        );
      },
    );
  }

  Widget _buildUpcomingExhibitions() {
    return FutureBuilder<List<Exhibition>>(
      future: _exhibitionService.getUpcomingExhibitions(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        
        if (snapshot.hasError) {
          return _buildErrorState(snapshot.error.toString());
        }
        
        final exhibitions = snapshot.data ?? [];
        if (exhibitions.isEmpty) {
          return _buildEmptyState('暂无即将开展的展览');
        }
        
        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: exhibitions.length,
          itemBuilder: (context, index) {
            final exhibition = exhibitions[index];
            return ExhibitionCard(
              exhibition: exhibition,
              onTap: () => _navigateToDetail(exhibition),
              onBookmark: () => _toggleBookmark(exhibition),
              showCountdown: true,
            );
          },
        );
      },
    );
  }

  Widget _buildVirtualExhibitions() {
    final virtualExhibitions = _exhibitions
        .where((e) => e.hasVirtualTour)
        .toList();
    
    if (virtualExhibitions.isEmpty) {
      return _buildEmptyState('暂无虚拟展厅');
    }
    
    return GridView.builder(
      padding: const EdgeInsets.all(16),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 0.8,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
      ),
      itemCount: virtualExhibitions.length,
      itemBuilder: (context, index) {
        final exhibition = virtualExhibitions[index];
        return _buildVirtualExhibitionCard(exhibition);
      },
    );
  }

  Widget _buildVirtualExhibitionCard(Exhibition exhibition) {
    return GestureDetector(
      onTap: () => _navigateToDetail(exhibition),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 3,
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      ThemeColors.primary.withOpacity(0.8),
                      ThemeColors.secondary.withOpacity(0.8),
                    ],
                  ),
                ),
                child: Stack(
                  children: [
                    const Center(
                      child: Icon(
                        Icons.view_in_ar,
                        size: 48,
                        color: Colors.white,
                      ),
                    ),
                    Positioned(
                      top: 8,
                      right: 8,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.9),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: const Text(
                          'VR',
                          style: TextStyle(
                            fontSize: 10,
                            fontWeight: FontWeight.bold,
                            color: Colors.deepOrange,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 2,
              child: Padding(
                padding: const EdgeInsets.all(12),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      exhibition.title,
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      exhibition.location,
                      style: TextStyle(
                        fontSize: 12,
                        color: ThemeColors.textSecondary,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState([String? message]) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.museum_outlined,
            size: 64,
            color: ThemeColors.textSecondary,
          ),
          const SizedBox(height: 16),
          Text(
            message ?? '暂无展览信息',
            style: TextStyle(
              fontSize: 16,
              color: ThemeColors.textSecondary,
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _loadExhibitions,
            child: const Text('重新加载'),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorState(String error) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red.withOpacity(0.6),
          ),
          const SizedBox(height: 16),
          Text(
            '加载失败',
            style: TextStyle(
              fontSize: 16,
              color: ThemeColors.textSecondary,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            error,
            style: TextStyle(
              fontSize: 12,
              color: ThemeColors.textSecondary,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _loadExhibitions,
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  void _showSearchDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('搜索展览'),
        content: TextField(
          autofocus: true,
          decoration: const InputDecoration(
            hintText: '输入展览名称或关键词',
            border: OutlineInputBorder(),
          ),
          onChanged: (value) {
            _searchQuery = value;
          },
          onSubmitted: (value) {
            Navigator.pop(context);
            _filterExhibitions();
          },
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _searchQuery = '';
              _filterExhibitions();
            },
            child: const Text('清除'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              _filterExhibitions();
            },
            child: const Text('搜索'),
          ),
        ],
      ),
    );
  }

  void _navigateToDetail(Exhibition exhibition) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ExhibitionDetailScreen(exhibition: exhibition),
      ),
    );
  }

  Future<void> _toggleBookmark(Exhibition exhibition) async {
    try {
      if (exhibition.isBookmarked) {
        await _exhibitionService.removeBookmark(exhibition.id);
      } else {
        await _exhibitionService.addBookmark(exhibition.id);
      }
      
      // 更新本地状态
      setState(() {
        final index = _exhibitions.indexWhere((e) => e.id == exhibition.id);
        if (index != -1) {
          _exhibitions[index] = _exhibitions[index].copyWith(
            isBookmarked: !_exhibitions[index].isBookmarked,
          );
        }
        _filterExhibitions();
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(exhibition.isBookmarked ? '已取消收藏' : '已收藏'),
          duration: const Duration(seconds: 1),
        ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: $e')),
      );
    }
  }
}